package com.hsck.order.kds.main.fragment.order

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.hsck.order.kds.R
import com.hsck.order.kds.base.isnoam.log.XLog
import com.hsck.order.kds.base.isnoam.view.BaseFragment
import com.hsck.order.kds.base.isnoam.view.HrSpacesItemDecoration
import com.hsck.order.kds.base.utils.NetworkUtil
import com.hsck.order.kds.databinding.FragmentOrderDynamicsBinding
import com.hsck.order.kds.main.MainActivity
import com.hsck.order.kds.main.dialog.SelectNumberDialog
import com.hsck.order.kds.main.dialog.SelectQuantityDialog
import com.hsck.order.kds.main.fragment.order.batch.DynamicBatchOrderingActivity
import com.hsck.order.kds.main.fragment.standard.bean.DishManager
import com.hsck.order.kds.main.fragment.standard.bean.TestListBean
import com.hsck.order.kds.main.itf.PageChangeListener
import com.hsck.order.kds.main.itf.UpdatableFragmentListener

/**
 * 订单动态
 */
class OrderDynamicsFragment : BaseFragment<FragmentOrderDynamicsBinding>(),
    UpdatableFragmentListener, PageChangeListener {
    override fun inflateBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentOrderDynamicsBinding {
        return FragmentOrderDynamicsBinding.inflate(inflater)
    }

    private var orderDynamicsAdapter: OrderDynamicsAdapter? = null
    private var selectQuantityDialog: SelectQuantityDialog? = null
    private var selectNumberDialog: SelectNumberDialog? = null
    private var itemBean: TestListBean? = null
    private var position: Int? = null
    private var columns: Int = 0

//    override fun loadDataOnce() {
//        super.loadDataOnce()
////        initRecyclerView(4)
//        showNoDataView {  }
//        orderDynamicsAdapter?.submitList(DishManager().getDishList())
//        binding.llRoot.visibility = View.VISIBLE
//    }

    override fun onResume() {
        super.onResume()
//        initRecyclerView(4)
        showNoDataView { }
        orderDynamicsAdapter?.submitList(DishManager().getDishList())
        binding.llRoot.visibility = View.VISIBLE
    }

    private fun setRecyclerViewLayout() {
        val linearLayoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        linearLayoutManager.isItemPrefetchEnabled = true
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.setItemViewCacheSize(20)
        binding.recyclerView.layoutManager = linearLayoutManager
        val spacingInPixels = resources.getDimensionPixelSize(R.dimen.order_column_spacing)
        binding.recyclerView.addItemDecoration(
            HrSpacesItemDecoration(
                spacingInPixels, 0
            )
        )
    }


    private fun initRecyclerView(columns: Int) {
        this.columns = columns
        orderDynamicsAdapter = OrderDynamicsAdapter(requireActivity(), columns)
        setRecyclerViewLayout()
        binding.recyclerView.adapter = orderDynamicsAdapter
        orderDynamicsAdapter!!.setDishOperationListener(object :
            OrderDynamicsAdapter.DishOperationListener {
            override fun onDishOperationAction(itemBean: TestListBean, position: Int) {
                this@OrderDynamicsFragment.itemBean = itemBean
                this@OrderDynamicsFragment.position = position
                //判断后台返回是否开启快速划菜
                if (itemBean.openDialog) {
                    when (itemBean.number) {
                        1 -> {
                            //请求划菜接口
                            XLog.i("请求划菜接口")
                        }

                        2 -> {
                            //显示选择1/2弹窗
//                            showQuantityDialog()
                        }

                        else -> {
                            //显示设置数量弹窗
//                            showNumberDialog()
                        }
                    }
                } else {
                    //请求划菜接口
                }
                XLog.i("数量: ${itemBean.number}, 是否弹窗: ${itemBean.openDialog}")
            }

            //批量划菜
            override fun onBatchDishAction(itemBean: TestListBean, position: Int) {
                val intent = Intent(activity, DynamicBatchOrderingActivity::class.java)
                startActivity(intent)
            }

            //单品划菜
            override fun onSingleItemSelectionAction(
                itemBean: TestListBean,
                childPosition: Int,
                childListSize: Int,
                adapter: OrderDynamicsDishItemsAdapter,
            ) {
                orderDynamicsAdapter?.removeItemAfterIndex(childPosition, adapter, childListSize)
            }
        })
    }

    /**
     * 数量大于2，设置划菜数量弹窗
     */
    private fun showNumberDialog() {
        if (selectNumberDialog == null) {
            selectNumberDialog = activity?.let { SelectNumberDialog(it) }
        }
        selectNumberDialog!!.show("测试数据", itemBean?.number.toString())
        selectNumberDialog!!.setSelectNumberListener(object :
            SelectNumberDialog.SelectNumberListener {
            override fun onSelectNumber(i: Int) {
                XLog.i("选择的数量为：$i")
            }
        })
    }

    /**
     * 1、2份数弹窗
     */
    private fun showQuantityDialog() {
        if (selectQuantityDialog == null) {
            selectQuantityDialog = activity?.let { SelectQuantityDialog(it) }
        }
        selectQuantityDialog!!.show("测试数据")
        selectQuantityDialog!!.setSelectQuantityListener(object :
            SelectQuantityDialog.SelectQuantityListener {
            override fun onSelectQuantity(i: Int) {
                XLog.i("选择的数量为：$i")
            }
        })
    }

    override fun onFragmentVisible() {
        activity?.let {
            if (it is MainActivity) {
                it.updatePageBtn(true)
            }
        }
        if (_binding != null) {
            if (NetworkUtil.isNetworkAvailable(requireActivity())) {
                hideLoadErrorView()
                orderDynamicsAdapter?.submitList(DishManager().getDishList())
                binding.llRoot.visibility = View.VISIBLE
            } else {
                showLoadErrorView {
                    XLog.i("加载失败，请点击重试")
                }
            }
        }
    }

    override fun onFragmentInvisible() {
        (activity as MainActivity).updatePageBtn(false)
    }

    private fun scrollRecyclerView(toRight: Boolean) {
        if (binding.recyclerView.layoutManager == null) {
            return
        }
        val layoutManager = binding.recyclerView.layoutManager as LinearLayoutManager
        val itemCount = layoutManager.itemCount
        // 获取第一个 item 的宽度
        val itemWidth = binding.recyclerView.getChildAt(0)?.width ?: 0
        // 获取 HrSpacesItemDecoration 的水平间距
        val decoration = binding.recyclerView.getItemDecorationAt(0) as HrSpacesItemDecoration
        val horizontalSpace = decoration.hSpace
        // 固定滑动列数
        val itemsToScroll = columns
        // 计算滑动的总距离（item 宽度 + 2 * 间距）
        val totalScrollDistance = itemsToScroll * (itemWidth + 2 * horizontalSpace)

        val currentPosition = layoutManager.findFirstVisibleItemPosition()

        // 判断剩余列数
        val remainingItems = itemCount - currentPosition

        if (toRight) {
            // 如果剩余列数小于2 * itemsToScroll，则滑动到最后一列
            if (remainingItems < 2 * itemsToScroll) {
                binding.recyclerView.smoothScrollToPosition(itemCount - 1)
            } else {
                binding.recyclerView.smoothScrollBy(totalScrollDistance, 0)
            }
        } else {
            // 如果当前索引小于2 * itemsToScroll，则滑动到第一列
            if (currentPosition < 2 * itemsToScroll) {
                binding.recyclerView.smoothScrollToPosition(0)
            } else {
                binding.recyclerView.smoothScrollBy(-totalScrollDistance, 0)
            }
        }
    }


    override fun onPageChange(isNext: Boolean) {
        scrollRecyclerView(isNext)
    }
}